/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.songs.listener;

import br.com.fatecpg.songs.entity.User;
import br.com.fatecpg.songs.util.FacesContextUtil;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;


/**
 *
 * @author Marcos Costa
 */
public class SecurityListener implements PhaseListener{
    private static final String LOGIN = "login";
    
    /**
     *
     * @param event
     */
    @Override  
    public void afterPhase(PhaseEvent event) {                 
        HttpSession session = (HttpSession) FacesContextUtil.getSession(false);        
        User user =  session != null? (User) session.getAttribute("user") : null;
        boolean timeout = session == null || session.isNew() || user == null;               
        if (timeout && FacesContextUtil.getNavigationUrl().contains("intranet")) {  
           FacesContextUtil.handleNavigation(LOGIN);                                    
        }  
    }  
 
    /**
     *
     * @param event
     */
    @Override  
    public void beforePhase(PhaseEvent event) {  
        
    }  

    /**
     *
     * @return
     */
    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
    
}
